<template>
  <div class="subtitle-selector">
    <el-row>
      <el-col :span="18">
        <!-- 搜索框 -->
        <el-input v-model="searchQuery" placeholder="搜索字幕文件" prefix-icon="Search" clearable class="search-input"
          @input="filterSubtitles" />
      </el-col>
      <el-col :span="6">
        <div 
        class="actions"
        >
          <el-button @click="refreshSubtitleList" :loading="loading">刷新</el-button>
        </div>

      </el-col>
    </el-row>


    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>

    <!-- 空状态 -->
    <div v-else-if="subtitleFiles.length === 0" class="empty-state">
      <el-empty description="暂无字幕文件" />
    </div>

    <!-- 文件列表 -->
    <div v-else class="subtitle-list">
      <el-scrollbar height="calc(80vh - 180px)">
        <div v-for="(file, index) in subtitleFiles" :key="index" class="subtitle-item" @click="selectSubtitle(file)"
          :class="{ 'selected': selectedSubtitleId === file.id }">
          <div class="subtitle-info">
            <div class="subtitle-name">{{ file.filename }}</div>
            <div class="subtitle-path">{{ file.file_path }}</div>
          </div>
          <el-button type="danger" size="small" :icon="Delete" circle class="delete-button"
            @click.stop="deleteSubtitle(file, index)" />
        </div>
      </el-scrollbar>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.page_size"
        :page-sizes="[10, 20, 50, 100]" layout="total, prev, pager, next" :total="pagination.total_count"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" :disabled="loading" background small />
    </div>


  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import footballService from '../services/footballService';
import { Delete } from '@element-plus/icons-vue';

const emit = defineEmits(['select-subtitle']);

// 状态
const subtitleFiles = ref([]);
const loading = ref(false);
const selectedSubtitleId = ref(null); // 改为用ID维护选中状态
const searchQuery = ref('');

// 分页参数
const pagination = ref({
  page: 1,
  page_size: 10,
  total_count: 0,
  total_pages: 0
});

// 过滤后的字幕列表
const filteredSubtitles = computed(() => {
  if (!searchQuery.value) return subtitleFiles.value;
  const query = searchQuery.value.toLowerCase();
  return subtitleFiles.value.filter(file =>
    file.filename.toLowerCase().includes(query) ||
    file.file_path.toLowerCase().includes(query)
  );
});

// 加载字幕列表
const loadSubtitleList = async () => {
  loading.value = true;

  const params = {
    page: pagination.value.page || 1,
    page_size: pagination.value.page_size || 10,
    search: searchQuery.value || undefined
  };

  try {
    const response = await footballService.getSubtitleList(params.page, params.page_size, params.search);
    subtitleFiles.value = response.data?.items || [];
    pagination.value = response.data?.pagination || pagination.value;
  } catch (error) {
    ElMessage.error('加载字幕文件失败: ' + error.message);
  } finally {
    loading.value = false;
  }
};

// 刷新字幕列表
const refreshSubtitleList = () => {
  pagination.value.page = 1;
  loadSubtitleList();
};

// 删除字幕
const deleteSubtitle = (file, index) => {
  ElMessageBox.confirm(
    `确定要删除字幕文件 "${file.filename}" 吗？`,
    '删除确认',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      return footballService.deleteIcon(file.id);
    })
    .then(() => {
      ElMessage.success('字幕文件删除成功');
      refreshSubtitleList();
    })
    .catch((err) => {
      if (err === 'cancel') {
        ElMessage.warning('已取消删除');
      } else {
        console.error('删除失败:', err);
        ElMessage.error('删除失败: ' + (err.message || '未知错误'));
      }
    });
};

// 处理页码变化
const handleCurrentChange = (page) => {
  pagination.value.page = page;
  loadSubtitleList();
};

// 处理每页条数变化
const handleSizeChange = (size) => {
  pagination.value.page_size = size;
  pagination.value.page = 1;
  loadSubtitleList();
};

// 选择字幕
const selectSubtitle = (file) => {
  selectedSubtitleId.value = file.id; // 保存字幕ID而非文件名
  emit('select-subtitle', file);
};

// 搜索时的处理
const filterSubtitles = () => {
  pagination.value.page = 1;
  loadSubtitleList();
};

// 组件挂载时加载数据
onMounted(() => {
  loadSubtitleList();
});

// 向外暴露方法
defineExpose({
  refreshSubtitleList,

  // 添加选择特定ID的字幕的方法
  selectSubtitleById(id) {
    selectedSubtitleId.value = id;
  },

  // 新增：更新特定字幕数据的方法
  updateSubtitleData(updatedSubtitle) {
    if (!updatedSubtitle || !updatedSubtitle.id) return;

    const index = subtitleFiles.value.findIndex(subtitle => subtitle.id === updatedSubtitle.id);
    if (index !== -1) {
      // 使用新数据更新列表中的对应项
      subtitleFiles.value[index] = { ...updatedSubtitle };
    }
  }
});
</script>

<style scoped>
.subtitle-selector {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.actions {
  display: flex;
  justify-content: flex-end;
}

.search-input {
  margin-bottom: 15px;
}

.loading-container,
.empty-state {
  padding: 30px 0;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-grow: 1;
}

.subtitle-list {
  margin-bottom: 20px;
  flex-grow: 1;
}

.subtitle-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border-radius: 4px;
  border: 1px solid #EBEEF5;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.2s;
}

.subtitle-item:hover {
  background-color: #F5F7FA;
}

.subtitle-item.selected {
  border-color: #409EFF;
  background-color: #ecf5ff;
}

.subtitle-name {
  font-weight: 500;
  margin-bottom: 5px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.subtitle-path {
  font-size: 12px;
  color: #909399;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 330px;
}

.delete-button {
  margin-left: 10px;
}

.pagination-container {
  margin-top: 15px;
  display: flex;
  justify-content: center;
}
</style>